package core.proto.search;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

/**
 * Class to perform search using Lucene. It is a wrapper around a (@link
 * org.apache.lucene.search.IndexSearcher} and a
 * {@link org.apache.lucene.queryParser.QueryParser}. It uses the analyzer used
 * by {@link core.proto.search.LuceneIndexCreationUtil} to parse the query
 * terms.
 */
public class LuceneSearchHelper {

	IndexSearcher searcher;
	QueryParser parser;

	public LuceneSearchHelper(File indexDir) throws IOException {
		Directory dir = FSDirectory.getDirectory(indexDir, false);
		searcher = new IndexSearcher(dir);
		parser = new QueryParser(LuceneIndexCreationUtil.CONTENT_FIELD,
				LuceneIndexCreationUtil.createAnalyzer());
	}

	/**
	 * Handler method for querying the index for the given query string.
	 * 
	 * @param queryString
	 * @return Set containing the absolute paths of the documents being
	 *         searched. The path is a primary key for the documents.
	 * @throws QueryNodeException
	 * @throws IOException
	 */
	public Set<String> search(String queryString) throws IOException {
		Query query;
		HashSet<String> result = new HashSet<String>();
		try {
			query = parser.parse(queryString);
		} catch (ParseException e) {
			return result;
		}
		Hits hits = searcher.search(query);

		for (int i = 0; i < hits.length(); ++i) {
			Document doc = hits.doc(i);
			Field field = doc.getField(LuceneIndexCreationUtil.FILENAME_FIELD);
			result.add(field.stringValue());
		}
		return result;
	}
}
